/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode* newHead = new ListNode;
        ListNode* curA = list1;
        ListNode* curB = list2;
        ListNode* cur = newHead;

        while (curA && curB)
        {
            if (curA->val <= curB->val)
            {
                cur->next = curA;
                curA = curA->next;
            }
            else
            {
                cur->next = curB;
                curB = curB->next;
            }
            cur = cur->next;
        }

        while (curA)
        {
            cur->next = curA;
            curA = curA->next;
            cur = cur->next;
        }
        while (curB)
        {
            cur->next = curB;
            curB = curB->next;
            cur = cur->next;
        }
        ListNode* head = newHead->next;
        delete newHead;
        return head;
    }
};